package com.deyang.util;

import android.app.Activity;
import android.app.Dialog;
import android.view.LayoutInflater;
import android.view.View;


import com.deyang.application.MyApplication;
import com.deyang.callback.HttpDownLoadCallBack;
import com.deyang.callback.ValueCallBack;
import com.deyang.maillist.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/9/29 0029.
 */
public class HttpUtil {

    private static final String TAG = "HttpUtil";

    private static final long connectTime = 30000L;
    private static final long readTime = 30000L;

    public static final String govResourceDoAdd_type = "type";
    public static final String govResourceDoAdd_parentId = "parentId";
    public static final String govResourceDoAdd_file = "File";
    private static final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private OkHttpClient okHttpClient;

    private Activity activity;
    private MyApplication mApp;


    public HttpUtil(Activity activity) {
        this.activity = activity;
        mApp = (MyApplication) activity.getApplication();
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(connectTime, TimeUnit.MILLISECONDS)
                .readTimeout(readTime, TimeUnit.MILLISECONDS);
//        CookiesManager cookieJar = new CookiesManager(activity);
        okHttpClient = builder.build();//其他配置
    }


    /**
     * 上传图片
     *
     * @param isShowLoadDialog
     * @param url
     * @param imgPathMap
     * @param callBack
     */
    public void uploadImg(final boolean isShowLoadDialog, String url, Map<String, String> parmasMap, Map<String, String> imgPathMap,
                          final ValueCallBack callBack) {
        Logger.e(TAG, "访问地址：url" + url);
        Logger.e(TAG, "访问参数：parmasMap" + parmasMap);
        Logger.e(TAG, "上传文件路径：imgPathMap" + imgPathMap);
        //加载对话框
        Dialog dialog = null;
        if (isShowLoadDialog) {
            View view = LayoutInflater.from(activity).inflate(R.layout.loading, null);
            dialog = new Dialog(activity, R.style.dialog);
            dialog.setContentView(view);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);
            dialog.show();
        }

        final Dialog finalDialog = dialog;

        //组件请求体
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.setType(MultipartBody.FORM);
        for (Iterator<String> iterator = parmasMap.keySet().iterator(); iterator.hasNext(); ) {
            String key = iterator.next();
            builder.addFormDataPart(key, parmasMap.get(key));
        }
        for (Iterator<String> iterator = imgPathMap.keySet().iterator(); iterator.hasNext(); ) {
            String key = iterator.next();
            File file = new File(imgPathMap.get(key));
            // 约定 key
            builder.addFormDataPart(key, file.getName(), RequestBody.create(MEDIA_TYPE_JPEG, file));
        }
        MultipartBody body = builder.build();

        //构建请求
        Request request = new Request.Builder()
                .url(url)//地址
                .post(body)//添加请求体
                .build();

        //请求
        okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Logger.e("uploadImg onResponse", "调用成功：" + response.toString());
                final String result = response.body().string();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    }
                });
            }

            @Override
            public void onFailure(Call call, final IOException e) {
            }

        });
    }


    /**
     * 下载文件
     *
     * @param url      下载文件地址
     * @param file     下载到指定路径
     * @param callBack 文件下载进度回调
     */
    public void downLoadFile(String url, final File file, final HttpDownLoadCallBack callBack) {
        //File file = new File(SDPath, "test.log");
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream(); //文件流
                    long total = response.body().contentLength(); //总长度
                    byte[] buf = new byte[2048];
                    int len = 0;
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        callBack.downLoadProgress(progress);
                    }
                    fos.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                            is = null;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                            fos = null;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    callBack.downLoadOver();
                }
            }
        });

    }
}
